package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.cari.oa.domain.SysDeptEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.domain.SysRoleEntity;
import com.cari.oa.domain.SysUserEntity;
import com.cari.oa.service.SysDeptService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysRoleService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
 * 系统用户controller
 * User: yexuhui
 * Date: 12-12-10
 * Time: 上午11:45
 */
@Controller
@SessionAttributes("username")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;
    @Resource
    private SysRoleService sysRoleService;
    @Resource
    private SysDictItemService sysDictItemService;
    
    @Resource
    private SysDeptService sysDeptService;
    
    public static final String MODULE_NAME = "SYS_USER_MANAGE";

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }

    @RequestMapping("/system/user/list.do")
    public String list(String enname, String cnname, Integer status, Integer curPage, ModelMap modelMap) {
        if(curPage == null) curPage = 1;
        long totalRecords = sysUserService.getCount(enname, cnname, status);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        
        List<SysUserEntity> userList = sysUserService.getPage(enname, cnname, status, curPage, Contants.PAGE_SIZE);
        List<SysDeptEntity> allDept = sysDeptService.getAll();
        Map<String, String> dNameMap = new HashMap<String, String>();
        for (SysDeptEntity dept : allDept) {
        	dNameMap.put(dept.getDeptNo(), dept.getDeptName());
		}
        
        modelMap.addAttribute("userList", userList);
        modelMap.addAttribute("dNameMap", dNameMap);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);

        modelMap.addAttribute("enname", enname);
        modelMap.addAttribute("cnname", cnname);
        modelMap.addAttribute("status", status);

        return "system/user/list";
    }
    
    @RequestMapping(value = "/system/user/view.do", method = RequestMethod.GET)
    public String enterView(String enname, ModelMap modelMap) {
    	SysUserEntity user = sysUserService.getByEnname(enname);
    	if(StrUtils.isNotEmpty(user.getDeptNo())){
    	   SysDeptEntity dept = sysDeptService.getByDeptNo(user.getDeptNo());
           modelMap.addAttribute("pDeptName", dept.getDeptName());
    	}
        modelMap.addAttribute("user", user);
        return "system/user/view";
    }    
    
    @RequestMapping(value = "/system/user/insert.do", method = RequestMethod.GET)
    public String enterInsert(String qs, ModelMap modelMap) {
    	List<String> treeList = sysDeptService.getTree(true);      
    	modelMap.addAttribute("treeList", treeList);
    	modelMap.addAttribute("qs", qs);
        return "system/user/insert";
    }
    
    @RequestMapping(value = "/system/user/insert.do", method = RequestMethod.POST)
    @ResponseBody
    public String postInsert(@ModelAttribute("username") String username, 
    		@Valid SysUserEntity sysUserEntity, BindingResult result) {
        if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());

        if (sysUserService.existByEnname(sysUserEntity.getEnname()))
            return Utils.errorJsonResp("系统用户英文名已存在");

        sysUserEntity.setPassword(Utils.md5(sysUserEntity.getPassword()));
        sysUserService.insert(sysUserEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "新增用户" + sysUserEntity.getEnname());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/user/edit.do", method = RequestMethod.GET)
    public String enterEdit(String enname, String qs, ModelMap modelMap) {
    	SysUserEntity user = sysUserService.getByEnname(enname);
    	List<String> treeList = sysDeptService.getTree(true);    
    	modelMap.addAttribute("treeList", treeList);
        modelMap.addAttribute("user", user);
    	modelMap.addAttribute("qs", qs);
        return "system/user/edit";
    }
    
    @RequestMapping(value = "/system/user/edit.do", method = RequestMethod.POST)
    @ResponseBody
    public String postEdit(@ModelAttribute("username") String username, 
    		@Valid SysUserEntity sysUserEntity, BindingResult result) {
    	if(result.hasFieldErrors())
            return Utils.errorJsonResp(result.getFieldError().getDefaultMessage());
        
        sysUserService.update(sysUserEntity);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "修改用户" + sysUserEntity.getEnname());
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/user/password.do", method = RequestMethod.GET)
    public String enterPassword(String enname, String qs, ModelMap modelMap) {
    	SysUserEntity user = sysUserService.getByEnname(enname);
        modelMap.addAttribute("user", user);
    	modelMap.addAttribute("qs", qs);
        return "system/user/password";
    }
    
    @RequestMapping(value = "/system/user/password.do", method = RequestMethod.POST)
    @ResponseBody
    public String postPassword(@ModelAttribute("username") String username, 
    		String enname, String password1, String password2) {
    	if(StrUtils.isEmpty(password1)) return Utils.errorJsonResp("密码不能为空");
    	if(StrUtils.isEmpty(password2)) return Utils.errorJsonResp("确认密码不能为空");
    	if(!password1.endsWith(password2)) return Utils.errorJsonResp("两次密码不匹配");
    	
    	sysUserService.changePassword(enname, password1);
    	
    	SysOperLogController.addOperLog(username, MODULE_NAME, "修改用户" + enname + "密码");
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/user/deactivate.do")
    @ResponseBody
    public String deactivate(@ModelAttribute("username") String username, String enname) {
    	SysUserEntity user = sysUserService.getByEnname(enname);
        if(user == null) return Utils.errorJsonResp("该用户已不存在，请刷新页面");

        user.setStatus(1);
        sysUserService.update(user);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "注销用户" + enname);
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/user/activate.do")
    @ResponseBody
    public String activate(@ModelAttribute("username") String username, String enname) {
    	SysUserEntity user = sysUserService.getByEnname(enname);
        if(user == null) return Utils.errorJsonResp("该用户已不存在，请刷新页面");

        user.setStatus(0);
        sysUserService.update(user);
        
        SysOperLogController.addOperLog(username, MODULE_NAME, "启用用户" + enname);
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/user/role.do", method = RequestMethod.GET)
    public String enterRole(String enname, String qs, ModelMap modelMap) {
    	List<SysRoleEntity> userRoles = sysRoleService.getRolesByUserName(enname);
    	List<SysRoleEntity> allRoles = sysRoleService.getAll();
    	
    	List<SysRoleEntity> diffRoles = new ArrayList<SysRoleEntity>();
    	for (SysRoleEntity allRoleEntity : allRoles) {
    		boolean find = false;
    		for (SysRoleEntity userRoleEntity : userRoles) {
				if(userRoleEntity.getId().equals(allRoleEntity.getId())) {
					find = true;
					break;
				}
			}
    		
    		if(!find) diffRoles.add(allRoleEntity);
		}
    	
    	modelMap.addAttribute("diffRoles", diffRoles);
    	modelMap.addAttribute("userRoles", userRoles);
        modelMap.addAttribute("enname", enname);
    	modelMap.addAttribute("qs", qs);
        return "system/user/role";
    }
    
    @RequestMapping(value = "/system/user/role.do", method = RequestMethod.POST)
    @ResponseBody
    public String postRole(@ModelAttribute("username") String username, String enname, String roles) {
    	if(StrUtils.isNotEmpty(roles)) {
    		String[] roleNames = roles.split(";");
    		sysRoleService.resetRolesByUserName(enname, Arrays.asList(roleNames));
    	}
    	
    	SysOperLogController.addOperLog(username, MODULE_NAME, "配置用户" + enname + "角色");
        return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/user/province.do", method = RequestMethod.GET)
    public String enterProvince(String enname, String qs, ModelMap modelMap){
    	List<SysDictItemEntity> provinces = sysDictItemService.getItemsByGroupName("province");
    	SysUserEntity user = sysUserService.getByEnname(enname);
    	
    	List<String> provinceList = new ArrayList<String>();
    	if(StrUtils.isNotEmpty(user.getProvince())){
	    	String[] strs = user.getProvince().split(",");
	    	for(String str : strs){
	    		provinceList.add(str);
	    	}
    	}
    	List<SysDictItemEntity> userProvince = new ArrayList<SysDictItemEntity>();
    	for(int i=0;i<provinces.size();i++ ){
    		if(provinceList.contains(provinces.get(i).getValue())){
    			userProvince.add(provinces.get(i));
    			provinces.remove(provinces.get(i));
    			i--;
    		}
    	}
    	
    	modelMap.addAttribute("provinceList", provinces);
    	modelMap.addAttribute("userProvince", userProvince);
    	modelMap.addAttribute("enname", enname);
    	modelMap.addAttribute("qs", qs);
    	return "system/user/province";
    }
    
    @RequestMapping(value = "/system/user/province.do", method = RequestMethod.POST)
    @ResponseBody
    public String postProvince(String enname, String province){
    	SysUserEntity user = sysUserService.getByEnname(enname);
    	user.setProvince(province);
    	sysUserService.update(user);
    	return Utils.normalJsonResp();
    }
    
    @RequestMapping(value = "/system/user/getUserByDeptNo.do", method = RequestMethod.POST)
    @ResponseBody
    public String getUserByDeptNo(String deptNo)
    {
    	List<SysUserEntity> users =  sysUserService.getAll();
    	List<SysUserEntity> temp = new ArrayList<SysUserEntity>();
    	for(SysUserEntity user : users)
    	{
    		if(user.getDeptNo() !=null && user.getDeptNo().equals(deptNo))
    		{
    			temp.add(user);
    		}
    	}
    	return JSON.toJSONString(temp);
    }
}
